//
//  ForumDetailsViewController.m
//  MoXiProject
//
//  Created by 沈晨宇 on 2017/7/31.
//  Copyright © 2017年 周筱雯. All rights reserved.
//

#import "ForumDetailsViewController.h"
#import "ForumViewModel.h"
#import "ForumDisCell.h"
#import "DicForumViewController.h"
@interface ForumDetailsViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSString* UID;
//    NSString* UToken;
    UIButton * rightButton;
    UIButton* huifuBut;
    UIButton* dianzanBut;
    UIView* headerView;
    UIView* downView;
    
    
    //    解析数据
    NSString* titleString;
    NSString* ReleasePeopleString;
    NSString* timeString;
    NSString* readNumString;
    NSString* imageString;
    NSString* contentString;
    NSString* commentCountString;
    NSString* isHitString;//是否点赞 0未赞 1已赞
    NSString* totalHitString;//点赞数
 
}
@property(nonatomic,strong)UITableView* detailsTable;
@property (nonatomic,strong) ForumViewModel * forumViewModel;
@end

@implementation ForumDetailsViewController

-(ForumViewModel *)forumViewModel{
    
    if (!_forumViewModel) {
        _forumViewModel = [[ForumViewModel alloc] init];
    }
    return _forumViewModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNav];
    [self getData];
  
    // Do any additional setup after loading the view.
}


-(void)initNav{
    
    [self.navigationItem setTitle:@"论坛详情"];
    [self.view setBackgroundColor:baseWhiteColor];
}

-(void)getData{
    
    if (UserInfoShare.isLogin==YES) {
        
        UID=UserInfoShare.userCenterModel.userID;
        NSLog(@"=====%@",UID);
//        UToken=UserInfoShare.userCenterModel.userToken;
//        NSLog(@"=====%@",UToken);
    }else{
        
        UID=@"";
//        UToken=@"";
        
    }
    [MXUtility showMBProgress:self.view message:LoadingText];
    
    [[self.forumViewModel forumsDetailRequestParameter:self.forumId userId:UID] subscribeNext:^(id result) {
        
        if([result[@"errorcode"] integerValue] == 0){
            
            titleString=result[@"result"][@"title"];
            ReleasePeopleString=result[@"result"][@"username"];
            timeString=result[@"result"][@"createTime"];
            readNumString=result[@"result"][@"readNum"];
            imageString=result[@"result"][@"imgUrl"];
            contentString=result[@"result"][@"content"];
            
            commentCountString=result[@"result"][@"comments"];
            totalHitString=result[@"result"][@"hit"];
            isHitString=result[@"result"][@"isHit"];
            
            [self initUI];
            [self.detailsTable reloadData];
            [self initDownView];
            
        }
        
        [MXUtility hideMBProgress:self.view];
    }error:^(NSError *error) {
        
        [MXUtility hideMBProgress:self.view];
        
    }];

}

-(void)initHeader{
    headerView=[[UIView alloc]init];
    
    UIImageView* iconImage=[UIImageView new];
    iconImage.layer.cornerRadius = 25;
    iconImage.layer.masksToBounds = YES;
    [iconImage sd_setImageWithURL:[NSURL URLWithString:imageString]placeholderImage:DEF_NORMAL_DEFAULT_IMAGE];
    [headerView addSubview:iconImage];
    [iconImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(50);
        make.top.equalTo(headerView).with.offset(12);
        make.leading.equalTo(headerView).with.offset(15);
    }];
    
    UILabel* nickLable=[UILabel new];
    nickLable.numberOfLines=0;
    nickLable.text=ReleasePeopleString;
    nickLable.font=DEF_MyFont(16);
    nickLable.textAlignment=NSTextAlignmentLeft;
    nickLable.textColor=baseBlackColor;
    [headerView addSubview:nickLable];
    [nickLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(150);
        make.height.mas_equalTo(16);
        make.top.equalTo(headerView).with.offset(16);
        make.leading.equalTo(iconImage.mas_trailing).with.offset(10);
    }];
    
    UILabel* timeLable=[UILabel new];
    timeLable.textColor=baseLightBlackColor;
    timeLable.font=DEF_MyFont(14);
    timeLable.textAlignment=NSTextAlignmentLeft;
    NSRange range = NSMakeRange(5,11);
    NSString* dateStr= [timeString substringWithRange:range];
    timeLable.text=[NSString stringWithFormat:@"%@发布",dateStr];
    [headerView addSubview:timeLable];
    [timeLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(150);
        make.height.mas_equalTo(14);
        make.top.equalTo(nickLable.mas_bottom).with.offset(14);
        make.leading.equalTo(iconImage.mas_trailing).with.offset(10);
    }];

    CGSize titleSize=[titleString boundingRectWithSize:CGSizeMake(DEF_DEVICE_WIDTH-20, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16]} context:nil].size;
    
    UILabel* titleLable=[UILabel new];
    titleLable.numberOfLines=0;
    titleLable.text=titleString;
    titleLable.font=DEF_MyFont(16);
    titleLable.textAlignment=NSTextAlignmentCenter;
    titleLable.textColor=baseBlackColor;
    [headerView addSubview:titleLable];
    [titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(DEF_DEVICE_WIDTH-20);
        make.height.mas_equalTo(titleSize.height+1);
        make.top.equalTo(iconImage.mas_bottom).with.offset(20);
        make.leading.equalTo(headerView).with.offset(10);
    }];
    
    CGSize contentLable2Size=[contentString boundingRectWithSize:CGSizeMake(DEF_DEVICE_WIDTH-30, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size;
    
    UILabel*  contentLable=[UILabel new];
    contentLable.text=contentString;
    contentLable.numberOfLines=0;
    contentLable.font=[UIFont systemFontOfSize:14];
    contentLable.textAlignment=NSTextAlignmentLeft;
    contentLable.textColor=baseLightBlackColor;
    [headerView addSubview:contentLable];
    [contentLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(DEF_DEVICE_WIDTH-30);
        make.height.mas_equalTo(contentLable2Size.height+1);
        make.top.equalTo(titleLable.mas_bottom).with.offset(20);
        make.leading.equalTo(headerView).with.offset(15);
    }];
    
    UILabel* readNumlable=[UILabel new];
    readNumlable.textColor=baseLightBlackColor;
    readNumlable.font=DEF_MyFont(14);
    readNumlable.text=[NSString stringWithFormat:@"阅读数:%@",readNumString];
    readNumlable.textAlignment=NSTextAlignmentRight;
    [headerView addSubview:readNumlable];
    
    [readNumlable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(75);
        make.height.mas_equalTo(14);
        make.top.equalTo(contentLable.mas_bottom).with.offset(30);
        make.trailing.equalTo(headerView).with.offset(-15);
    }];
 
    headerView.frame=CGRectMake(0, 0, DEF_DEVICE_WIDTH, 50+12+20+titleSize.height+1+20+contentLable2Size.height+1+30+14+10);
    self.detailsTable.tableHeaderView=headerView;
}

-(void)initUI{

    self.detailsTable=[UITableView new];
    self.detailsTable.delegate=self;
    self.detailsTable.dataSource=self;
    self.detailsTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.detailsTable];
    
    if(iPhoneX){
        [self.detailsTable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(DEF_DEVICE_WIDTH);
            make.height.mas_equalTo(DEF_DEVICE_HEIGHT-88-50-34);
            make.top.equalTo(self.view).with.offset(0);
            make.leading.equalTo(self.view).with.offset(0);
        }];
        
    }else{
        
        [self.detailsTable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(DEF_DEVICE_WIDTH);
            make.height.mas_equalTo(DEF_DEVICE_HEIGHT-64-50);
            make.top.equalTo(self.view).with.offset(0);
            make.leading.equalTo(self.view).with.offset(0);
        }];
        
    }

    [self initHeader];

}

-(void)initDownView{
    
    downView=[UIView new];
    [self.view addSubview:downView];
    
    if(iPhoneX){
        [downView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(DEF_DEVICE_WIDTH);
            make.height.mas_equalTo(50);
            make.bottom.equalTo(self.view.mas_bottom).with.offset(-34);
            make.leading.equalTo(self.view).with.offset(0);
        }];
        
    }else{
        [downView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(DEF_DEVICE_WIDTH);
            make.height.mas_equalTo(50);
            make.bottom.equalTo(self.view.mas_bottom).with.offset(0);
            make.leading.equalTo(self.view).with.offset(0);
        }];
        
    }
    
    UIView* line2=[UIView new];
    line2.backgroundColor=DEF_COLOR_F0F0F0;
    [downView addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(DEF_DEVICE_WIDTH);
        make.height.mas_equalTo(1);
        make.top.equalTo(downView).with.offset(1);
        make.leading.equalTo(downView).with.offset(0);
    }];
    
    UIView* line=[UIView new];
    line.backgroundColor=DEF_COLOR_F0F0F0;
    [downView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(30);
        make.top.equalTo(downView).with.offset(10);
        make.leading.equalTo(downView).with.offset(DEF_DEVICE_WIDTH/2);
    }];
    
    huifuBut=[UIButton buttonWithType:UIButtonTypeCustom];
    [huifuBut setImage:[UIImage imageNamed:@"huifu_"] forState:UIControlStateNormal];
    [huifuBut setImage:[UIImage imageNamed:@"huifu_"] forState:UIControlStateHighlighted];
    [huifuBut setTitle:[NSString stringWithFormat:@"评论%@",commentCountString] forState:UIControlStateNormal];
    [huifuBut addTarget:self action:@selector(commentsButClick) forControlEvents:UIControlEventTouchUpInside];
    [huifuBut setTitleColor:baseLightBlackColor forState:UIControlStateNormal];
    [huifuBut setImageEdgeInsets:UIEdgeInsetsMake(0, 30, 0, 50)];
    [huifuBut setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [downView addSubview:huifuBut];
    [huifuBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(DEF_DEVICE_WIDTH/2);
        make.height.mas_equalTo(50);
        make.top.equalTo(downView).with.offset(0);
        make.leading.equalTo(downView).with.offset(0);
    }];
    
    dianzanBut=[UIButton buttonWithType:UIButtonTypeCustom];
    
    if ([isHitString isEqual:@"1"]) {
        
        [dianzanBut setImage:[UIImage imageNamed:@"dianzanHong_"] forState:UIControlStateNormal];
        [dianzanBut setImage:[UIImage imageNamed:@"dianzanHong_"] forState:UIControlStateHighlighted];
        
    }else{
        
        [dianzanBut setImage:[UIImage imageNamed:@"dianzanHui_"] forState:UIControlStateNormal];
        [dianzanBut setImage:[UIImage imageNamed:@"dianzanHui_"] forState:UIControlStateHighlighted];
    }
    
    [dianzanBut setTitle:[NSString stringWithFormat:@"赞%@",totalHitString] forState:UIControlStateNormal];
    [dianzanBut addTarget:self action:@selector(ThumbButClick) forControlEvents:UIControlEventTouchUpInside];
    [dianzanBut setTitleColor:baseLightBlackColor forState:UIControlStateNormal];
    [dianzanBut setImageEdgeInsets:UIEdgeInsetsMake(0, 30, 0, 50)];
    [dianzanBut setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [downView addSubview:dianzanBut];
    [dianzanBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(DEF_DEVICE_WIDTH/2);
        make.height.mas_equalTo(50);
        make.centerY.equalTo(huifuBut);
        make.leading.equalTo(line.mas_trailing).with.offset(0);
    }];
    
}

-(void)commentsButClick{
    
    if (UserInfoShare.isLogin==YES) {

        DicForumViewController* vc=[[DicForumViewController alloc]init];
        vc.forumID=self.forumId;
        vc.backBlock = ^(void){
            
            [downView removeFromSuperview];
             self.forumViewModel.forumDisArrayList = [[NSMutableArray alloc] initWithCapacity:0];
            [self getData];
           
        };
        
        [self.navigationController pushViewController:vc animated:YES];

    }else{
        
        [MXUtility showTips:@"请先前去登录"];
        
    }
}
-(void)ThumbButClick{
    
    if (UserInfoShare.isLogin==YES) {
        
        if ([isHitString isEqualToString:@"1"]) {
            
            [MXUtility showTips:@"你已经点赞过这条帖子了"];
            
        }else{
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否对这条帖子点赞？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction* action){
                [MXUtility showMBProgress:self.view message:LoadingText];
                
                [[self.forumViewModel saveForumThumbsRequestParameter:UserInfoShare.userCenterModel.userID forumId:self.forumId] subscribeNext:^(id result) {
                    
                    if([result[@"errorcode"] integerValue] == 0){
                        
                        [MXUtility showTips:@"点赞成功"];
                        [dianzanBut setImage:[UIImage imageNamed:@"dianzanHong_"] forState:UIControlStateNormal];
                        [dianzanBut setImage:[UIImage imageNamed:@"dianzanHong_"] forState:UIControlStateHighlighted];
                        isHitString=@"1";
                        
                        int Count=[totalHitString intValue] +1 ;
                        
                        NSLog(@"-----%d,",Count);
                        [dianzanBut setTitle:[NSString stringWithFormat:@"赞%d",Count] forState:UIControlStateNormal];
                        
                    }else{
                        
                        [MXUtility showTips:@"点赞失败，请稍后再试"];
                        
                    }
                    
                    [MXUtility hideMBProgress:self.view];
                }error:^(NSError *error) {
                    
                    [MXUtility hideMBProgress:self.view];
                    
                }];
                
            }];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction* action){
                
            }];
            [alert addAction:cancel];
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            
        }
        
    }else{
    
        [MXUtility showTips:@"请先前去登录"];

    }
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.forumViewModel.forumDisArrayList.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_DEVICE_WIDTH, 36)];
    view.backgroundColor=DEF_COLOR_F0F0F0;
    UILabel* lable=[[UILabel alloc]initWithFrame:CGRectMake(15, 14, DEF_DEVICE_WIDTH, 12)];
    lable.font=DEF_MyFont(14);
    lable.textColor=baseLightBlackColor;
    lable.text=@"最新评论";
    [view addSubview:lable];
    
    return view;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 36;
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat sectionHeaderHeight = 36;
    
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"ForumDisCell";
    ForumDisCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[ForumDisCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    cell.model=self.forumViewModel.forumDisArrayList[indexPath.row];
    [cell.report addTarget:self action:@selector(report) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)report{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否举报这条评论？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction* action){
        
        [MXUtility showMBProgress:self.view message:LoadingText];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [MXUtility hideMBProgress:self.view];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"举报成功" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction* action){
                
            }];
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            
        });
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction* action){
        
    }];
    [alert addAction:cancel];
    [alert addAction:sure];
    [self presentViewController:alert animated:YES completion:nil];
    
}

@end
